package in.iqing.control.helper;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.squareup.otto.Bus;

public class EventHelper {

	private Bus bus;
	private Handler mainHandler;
	private static EventHelper singleton;

	private static final int POST = 1;

	public EventHelper() {
		this.bus = new Bus();
		this.mainHandler = new EventHandler(Looper.getMainLooper());
	}

	public static synchronized EventHelper getSingleton() {
		if (singleton == null) {
			singleton = new EventHelper();
		}

		return singleton;
	}

	public void post(Object o) {
		if (Looper.myLooper() != Looper.getMainLooper()) {
			Message msg = mainHandler.obtainMessage();
			msg.what = POST;
			msg.obj = o;
			mainHandler.sendMessage(msg);
		} else {
			bus.post(o);
		}
	}

	public void register(Object o) {
		bus.register(o);
	}

	public void unregister(Object o) {
		bus.unregister(o);
	}

	private class EventHandler extends Handler {

		public EventHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case POST:
					bus.post(msg.obj);
					break;
			}
		}
	}
}
